import { useCallback, useContext, useRef, useState } from 'react';
import { Search } from '../../../baseComponent';
import { BaseHelp, HelpContext, Table, Tabs } from '../../../functionalComponent';
import { compHoc, getGlobalConfig, Layout, iup, useRefCallback } from '../../../util';
import { getHelpBeforeOpen } from '../common';
import { IUserHelp } from './interface';
import UserCompanyHelp from './UserCompanyHelp';
import UserProjectHelp from './UserProjectHelp';
import { findFilterIndexes } from './utils';

const { Option } = Tabs;
const { Header, Footer, MultipleButtons } = BaseHelp;

const tableProps: any = {
  rowSelected: false,
  rowChecked: true,
  cache: false,
  headerMenu: false,
  style: { borderStyle: 'solid', borderColor: 'var(--border-color-split, #f0f0f0)', borderWidth: 1 }
};

function HelpContent() {
  const {
    request,
    ok,
    contentParams: {
      showTree = true,
      getFieldValue,
      columns,
      helpTitle,
      helpId,
      selectedArray,
      multiple,
      footer,
      treeProps,
      isProject
    },
    locale,
    randomKey
  } = useContext<any>(HelpContext);
  const btnRef = useRef<any>();

  // 默认显示的tab
  const [activeKey, setActiveKey] = useState(isProject ? '0' : '1');
  const [flag, setFlag] = useState(false);
  const rightTable = useRef<any>();
  const borderStyle = activeKey === '0' ? '1px solid var(--border-color-split, #f0f0f0)' : '1px solid transparent';

  const getTable = useCallback(() => iup.compIns[`${helpId}_${randomKey}_${activeKey}`].getApi(), [activeKey]);

  const getResult: any = () => {
    if (multiple) {
      const result = rightTable.current
        .getApi()
        .getRows()
        .map((r) => ({
          value: getFieldValue(r),
          label: getFieldValue(r, 'label'),
          origin: { ...r, activeKey }
        }));
      return result.length > 0 ? result : undefined;
    } else {
      const value = getTable().getSelectedData()[0];
      if (value) {
        return { value: getFieldValue(value), label: getFieldValue(value, 'label'), origin: { ...value, activeKey } };
      }
      return undefined;
    }
  };
  const toRight = (values: any) => {
    if (multiple) {
      btnRef.current.toRight(values);
    } else {
      ok(getResult());
    }
  };

  const onSearch = (value: string) => {
    if (['0', '1'].includes(activeKey)) {
      getTable().query({ keyword: value });
    } else {
      getTable().filter(value);
    }
  };

  const tabBarExtraContent = (
    <Search size="small" allowClear placeholder={locale.searchPlaceholder} onSearch={onSearch} />
  );

  tableProps.checkbox = multiple ? 'checked' : false;
  tableProps.rowSelected = !multiple;
  tableProps.rowChecked = multiple;

  const onDataLoad = useRefCallback((table) => {
    const { dataSource = [] } = table.getState() || {};
    const selectIndex = findFilterIndexes(dataSource, (it) => (selectedArray || []).map((x) => x.id).includes(it.id));
    table.setSelected(selectIndex);
  });

  const renderTable = (index) => {
    return (
      <Table
        {...tableProps}
        style={{ ...tableProps.style, borderTopWidth: 0 }}
        id={`${helpId}_${randomKey}_${index}`}
        columns={columns}
        pagination={{
          height: 32,
          showQuickJumper: false,
          align: 'left',
          targetContainer: multiple ? `${helpId}_${randomKey}_pagination` : ''
        }}
        onRow={(rowIndex, table) => ({
          onDoubleClick: () => toRight([table.getRow(rowIndex)])
        })}
        autoLoad={!index && activeKey === '0' && !flag}
        request={(params) => request(Object.assign({}, params, { isProjectHelp: activeKey === '0' }))}
        response={(res) => ({ total: res.total ?? 0, record: res.list || [] })}
        onDataLoad={onDataLoad}
      />
    );
  };

  return (
    <Layout>
      <Header title={helpTitle || '用户帮助'} />
      <Layout.Flex direction="row" style={{ padding: '0 5px', borderBottom: multiple ? borderStyle : 0 }}>
        <Layout.Flex flex={2}>
          <Tabs
            className="fit-height"
            size="small"
            onChange={(key) => {
              setActiveKey(key);
              setFlag(true);
            }}
            tabBarExtraContent={tabBarExtraContent}
            activeKey={activeKey}
          >
            {isProject && (
              <Option tab={<span style={{ padding: '0 8px' }}>项目</span>} key="0">
                <UserProjectHelp renderTable={renderTable} multiple={multiple} />
              </Option>
            )}
            <Option tab={<span style={{ padding: '0 8px' }}>公司</span>} key="1">
              <UserCompanyHelp
                borderStyle={borderStyle}
                treeProps={treeProps}
                renderTable={renderTable}
                getTable={getTable}
                multiple={multiple}
                showTree={showTree}
              />
            </Option>
          </Tabs>
        </Layout.Flex>
        {multiple && (
          <MultipleButtons
            getRowKey={getFieldValue}
            outRef={btnRef}
            getActiveTable={getTable}
            getResultTable={() => rightTable.current.getApi()}
          />
        )}
        {multiple && (
          <Layout.Flex style={{ paddingTop: 7, paddingBottom: ['0', '1'].includes(activeKey) ? 32 : 0 }}>
            <Table
              {...tableProps}
              columns={columns}
              dataSource={selectedArray}
              ref={rightTable}
              onRow={(rowIndex) => ({
                onDoubleClick: () => btnRef.current.toLeft(rowIndex)
              })}
            />
            <div
              id={`${helpId}_${randomKey}_pagination`}
              style={{
                position: 'absolute',
                left: activeKey === '0' ? 5 : 205,
                right: 15,
                borderLeft: borderStyle,
                paddingLeft: 10
              }}
            />
          </Layout.Flex>
        )}
      </Layout.Flex>
      <Footer getResult={getResult}>{footer && <span style={{ flex: 1, width: 0 }} children={footer} />}</Footer>
    </Layout>
  );
}

/**
 * 用户帮助
 */
export const UserHelp = compHoc<IUserHelp>((props) => {
  const cacheHelpInfo = useRef({ data: null, p: null });
  const {
    valueField = 'userNo',
    labelField = 'userName',
    isProject = false,
    showTree = true,
    displayField,
    userCodeField,
    title,
    multiple = false,
    modalProps,
    footer,
    params: treeParams,
    treeRequest,
    beforeRequest: beforeTreeRequest,
    userRequest,
    userParams = {},
    columns,
    onBeforeOpen,
    ...others
  } = props;
  const helpId = 'user';
  const otherProps: any = others;
  otherProps.onBeforeOpen = useRefCallback(async () => {
    const [status, helpInfo] = await getHelpBeforeOpen({ onBeforeOpen, cacheHelpInfo });
    if (iup.isObject(helpInfo)) {
      return helpInfo;
    }
    return status;
  });
  otherProps.request = useRefCallback(
    async ({ pageIndex, pageSize, keyword, treeNodes, containLowOrgUser = false, isProjectHelp }) => {
      const data: any = {
        ...userParams,
        containLowOrgUser,
        pageNum: pageIndex,
        pageSize
      };
      isProjectHelp && (data.projType = true);
      keyword && (data.query = keyword);
      if (treeNodes && treeNodes.length > 0) {
        const { code, leafType } = treeNodes[0];
        const keys = { PROJECT: 'belongProject', DEPT: 'belongDept', ORG: 'belongOrg' };
        if (!data[keys[leafType]]) {
          data[keys[leafType]] = code;
        }
      }
      if (userRequest) {
        return await userRequest(data);
      }
      const res = await iup.request.body({
        url: '/basedata/user/getUserPages',
        data
      });
      if (res?.code === 0) return res?.data;
      return { list: [], total: 0 };
    }
  );
  otherProps.valueField = valueField;
  otherProps.userCodeField = userCodeField;
  otherProps.labelField = labelField || displayField;
  // 自定义modal弹出窗需要使用的参数
  otherProps.contentParams = {
    footer,
    helpId,
    showTree,
    multiple,
    valueField,
    labelField: otherProps.labelField,
    treeProps: {
      params: treeParams,
      beforeRequest: beforeTreeRequest,
      treeRequest
    },
    columns: columns ?? [
      { dataIndex: 'userNo', title: '用户编号' },
      { dataIndex: 'userName', title: '用户名称' },
      { dataIndex: 'belongOrgName', title: '所属组织' },
      {
        dataIndex: 'userJobList',
        tooltip: 'render',
        title: '所属部门',
        render({ value }) {
          return <span className="nowrap">{value?.map((v) => v.deptName).join(',')}</span>;
        }
      },
      {
        dataIndex: 'projectPost',
        title: '岗位'
      }
    ],
    isProject
  };
  if (title) {
    otherProps.contentParams.helpTitle = title;
  }
  if (onBeforeOpen) {
    otherProps.cache = false;
  }

  const { width, height } = getGlobalConfig().default.helpConfig;
  return (
    <BaseHelp
      {...otherProps}
      modal
      helpContent={HelpContent}
      multiple={multiple}
      modalProps={{ width, height, ...modalProps }}
    />
  );
}, 'UserHelp');
